package com.kayb.patterns.structural;

/**
 * 装饰者模式，扩展类功能，动态为Source添加功能
 * 实现：装饰类持有Source的一个实例，并实现相同的接口。
 * @author huangkaibin
 * @date 2018-08-28
 **/
public class Decorator {

    interface Troll {
        void attack();
        int getAttackPower();
        void fleeBattle();
    }

    static class SimpleTroll implements Troll {

        @Override
        public void attack() {
            System.out.println("The troll tries to grab you!");
        }

        @Override
        public int getAttackPower() {
            return 10;
        }

        @Override
        public void fleeBattle() {
            System.out.println("The troll shrieks in horror and runs away!");
        }
    }

    static class ClubbedTroll implements Troll {

        private Troll decorated;

        public ClubbedTroll(Troll decorated) {
            this.decorated = decorated;
        }

        @Override
        public void attack() {
            decorated.attack();
            System.out.println("The troll swings at you with a club!");
        }

        @Override
        public int getAttackPower() {
            return decorated.getAttackPower() + 10;
        }

        @Override
        public void fleeBattle() {
            decorated.fleeBattle();
        }
    }

    public static void main(String[] args) {
        // simple troll
        Troll troll = new SimpleTroll();
        troll.attack(); // The troll tries to grab you!
        troll.fleeBattle(); // The troll shrieks in horror and runs away!

        // change the behavior of the simple troll by adding a decorator
        troll = new ClubbedTroll(troll);
        troll.attack(); // The troll tries to grab you! The troll swings at you with a club!
        troll.fleeBattle(); // The troll shrieks in horror and runs away!
    }

}
